<template>
  <div class="app-container">
    <!-- 左侧树形菜单 -->
    <div class="tree-panel">
      <div class="head-container">
        <el-input
          v-model="projectName"
          placeholder="请输入培训项目"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
          @keyup.enter.native="filterTree"
        />
      </div>
      <el-tree
        ref="tree"
        :data="projectOptions"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        node-key="id"
        default-expand-all
        highlight-current
        @node-click="handleNodeClick"
      />
    </div>

    <!-- 右侧表格 -->
    <el-col :span="20" style="padding: 20px">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="80px"
        style="margin-bottom: 20px"
      >
        <!-- 考试关键词 -->
        <el-form-item label="考试" prop="paperConfigName">
          <el-input
            v-model="queryParams.paperConfigName"
            placeholder="请输入考试关键词"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 200px"
          />
        </el-form-item>

        <!-- 创建时间范围 -->
        <el-form-item label="创建时间" prop="createTimeRange">
          <el-date-picker
            v-model="queryParams.createTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            style="width: 240px"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="24">
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
            "
          >
            <!-- 左侧按钮 -->
            <div style="display: flex; gap: 10px">
              <el-button type="warning" plain @click="handleExport"
                >导出</el-button
              >
              <el-button type="primary" plain @click="handleAdd"
                >创建考试</el-button
              >
              <el-button
                type="success"
                plain
                :disabled="single"
                @click="handleUpdate"
                >编辑考试</el-button
              >
              <el-button
                type="danger"
                plain
                :disabled="multiple"
                @click="handleDelete"
                >删除考试</el-button
              >
            </div>

            <!-- 右侧按钮 -->
            <div style="display: flex; gap: 10px">
              <column-config-dialog-vue
                :showSearch.sync="showSearch"
                :columns="tableColumns"
                @queryTable="getList"
              ></column-config-dialog-vue>
            </div>
          </div>
        </el-col>
      </el-row>

      <el-table
        v-loading="loading"
        :data="paperConfigList"
        @selection-change="handleSelectionChange"
      >
        <!-- 选择列 -->
        <el-table-column type="selection" width="55" align="center" />

        <!-- 考试 -->
        <el-table-column
          label="考试"
          align="center"
          prop="paperConfigName"
          v-if="
            tableColumns.find((col) => col.key === 'paperConfigName').visible
          "
        />

        <!-- 培训项目 -->
        <el-table-column
          label="培训项目"
          align="center"
          prop="projectMap"
          v-if="tableColumns.find((col) => col.key === 'projectMap').visible"
        />

        <!-- 命题题组 -->
        <el-table-column
          label="命题题组"
          align="center"
          prop="trainingProjectId"
          v-if="
            tableColumns.find((col) => col.key === 'trainingProjectId').visible
          "
        />

        <!-- 命题题量 -->
        <el-table-column
          label="命题题量"
          align="center"
          prop="total_count"
          v-if="tableColumns.find((col) => col.key === 'total_count').visible"
        />

        <!-- 单选题 -->
        <el-table-column
          label="单选题"
          align="center"
          prop="singleChoiceCount"
          v-if="
            tableColumns.find((col) => col.key === 'singleChoiceCount').visible
          "
        />

        <!-- 多选题 -->
        <el-table-column
          label="多选题"
          align="center"
          prop="multipleChoiceCount"
          v-if="
            tableColumns.find((col) => col.key === 'multipleChoiceCount')
              .visible
          "
        />

        <!-- 判断题 -->
        <el-table-column
          label="判断题"
          align="center"
          prop="judgmentCount"
          v-if="tableColumns.find((col) => col.key === 'judgmentCount').visible"
        />

        <!-- 合计题量 -->
        <el-table-column
          label="合计题量"
          align="center"
          prop="totalCount"
          v-if="tableColumns.find((col) => col.key === 'totalCount').visible"
        />

        <!-- 创建人 -->
        <el-table-column
          label="创建人"
          align="center"
          prop="createBy"
          v-if="tableColumns.find((col) => col.key === 'createBy').visible"
        />

        <!-- 创建时间 -->
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          v-if="tableColumns.find((col) => col.key === 'createTime').visible"
        >
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>

        <!-- 是否考试过 -->
        <el-table-column
          label="是否考试过"
          align="center"
          prop="hasExamined"
          v-if="tableColumns.find((col) => col.key === 'hasExamined').visible"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.has_examined"
              :value="scope.row.hasExamined"
            />
          </template>
        </el-table-column>

        <!-- 使用次数 -->
        <el-table-column
          label="使用次数"
          align="center"
          prop="usageCount"
          v-if="tableColumns.find((col) => col.key === 'usageCount').visible"
        />

        <!-- 备注 -->
        <el-table-column
          label="备注"
          align="center"
          prop="paperConfigRemark"
          v-if="
            tableColumns.find((col) => col.key === 'paperConfigRemark').visible
          "
        />

        <!-- 操作 -->
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          v-if="tableColumns.find((col) => col.key === 'operation').visible"
        >
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)">
              编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              v-hasPermi="['examination:paperConfig:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改试卷信息设置对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="open"
        style="width: 100%"
        append-to-body
        :close-on-click-modal="false"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <!-- 水平布局：试题名称 + 项目类别 -->
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="试题名称" prop="paperConfigName">
                <el-input
                  v-model="form.paperConfigName"
                  placeholder="请输入试题名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目类别" prop="trainingProjectId">
                <el-cascader
                  style="width: 100%"
                  v-model="form.trainingProjectId"
                  :options="projectOptions"
                  :props="{
                    checkStrictly: true,
                    emitPath: false, //只传入子节点的id
                    value: 'id',
                    label: 'label',
                    children: 'children',
                  }"
                  placeholder="请选择项目类别"
                  clearable
                  @change="handleProjectChange"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 题组配置表格 -->
          <el-table
            :data="form.paperConfigGroupList || []"
            style="width: 100%"
            border
            size="small"
            :show-summary="true"
            :summary-method="getSummaryMethod"
          >
            <el-table-column label="考试题组" width="220">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.groupName"
                  placeholder="请选择题组"
                  filterable
                  @change="(val) => handleGroupChange(val, scope.row)"
                >
                  <el-option
                    v-for="item in getGroupOptions(scope.row.type)"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="题组类型" width="150">
              <template slot-scope="scope">
                <el-select v-model="scope.row.groupType">
                  <el-option
                    v-for="item in dict.type.question_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="题组题量" width="100">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.questionCount"
                  :min="0"
                  style="width: 100%"
                  controls-position="right"
                  size="small"
                  :disabled="true"
                />
              </template>
            </el-table-column>

            <el-table-column label="设置题量" width="160">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.setCount"
                  :min="0"
                  style="width: 100%"
                />
              </template>
            </el-table-column>

            <el-table-column label="每题分数" width="150">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.scorePerQuestion"
                  :min="0"
                  style="width: 100%"
                />
              </template>
            </el-table-column>

            <el-table-column label="分数合计" width="100">
              <template slot-scope="scope">
                {{
                  (scope.row.setCount || 0) * (scope.row.scorePerQuestion || 0)
                }}
              </template>
            </el-table-column>

            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="removeRow(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- 添加按钮 -->
          <el-button
            type="text"
            size="small"
            style="margin-top: 10px"
            @click="addRow"
          >
            增加一项
          </el-button>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </el-dialog>
    </el-col>
  </div>
</template>

<script>
import {
  listPaperConfig,
  getPaperConfig,
  delPaperConfig,
  addPaperConfig,
  updatePaperConfig,
  getPaperCofigList,
  addPaperConfigInfo,
  editPaperConfig,
  getPaperConfigInfo,
} from "@/api/examination/paperConfig";
import { getListInfo } from "@/api/examination/questionGroup";
import { projectTreeSelect } from "@/api/training/projects";
import ColumnConfigDialogVue from "../../../components/ColumnConfig/ColumnConfigDialog.vue";

export default {
  name: "PaperConfig",
  components: { ColumnConfigDialogVue },
  dicts: ["has_examined", "question_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷信息设置表格数据
      paperConfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectMap: null,
        hasExamined: null,
        usageCount: null,
        scorePerQuestion: null,
        totalScore: null,

        paperConfigName: null, // 新增：考试关键词
        createTimeRange: null, // 新增：创建时间范围
      },
      // 表单参数
      form: {
        //新增/修改表单数据
        paperConfigGroupList: [
          {
            groupName: "",
            type: "",
            count: 0, // 后端返回的题组题量（不可编辑）
            setCount: 0, // 用户设置的题量（可编辑）
            scorePerQuestion: 0,
            totalScore: 0, // 自动计算：setCount * scorePerQuestion
          },
        ],
      },
      // 表单校验
      rules: {
        paperConfigName: [
          { required: true, message: "试题名称不能为空", trigger: "blur" },
        ],
        trainingProjectId: [
          { required: true, message: "项目类别不能为空", trigger: "change" },
        ],
      },

      //新增数据定义
      //树形结构数据
      // 所有部门树选项
      projectName: "",
      projectOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 列配置弹窗
      tableColumns: [
        { key: "paperConfigId", label: "考试", visible: true },
        { key: "paperConfigName", label: "考试", visible: true },
        { key: "projectMap", label: "培训项目", visible: true },
        { key: "trainingProjectId", label: "命题题组", visible: true },
        { key: "total_count", label: "命题题量", visible: true },
        { key: "singleChoiceCount", label: "单选题", visible: true },
        { key: "multipleChoiceCount", label: "多选题", visible: true },
        { key: "judgmentCount", label: "判断题", visible: true },
        { key: "totalCount", label: "合计题量", visible: true },
        { key: "createBy", label: "创建人", visible: true },
        { key: "createTime", label: "创建时间", visible: true },
        { key: "hasExamined", label: "是否考试过", visible: true },
        { key: "usageCount", label: "使用次数", visible: true },
        { key: "paperConfigRemark", label: "备注", visible: true },
        { key: "operation", label: "操作", visible: true },
      ],
      // 缓存字典数据
      dictCache: {
        has_examined: {},
      },
      customGroupOptions: {}, // 存储用户自定义的题组选项
    };
  },
  created() {
    this.getList();
    this.getProjectTree();
    this.$nextTick(async () => {
      await this.loadDicts();
    });
    // 确保 form 对象初始化
    if (!this.form) {
      this.form = { paperConfigGroupList: [] };
    } else if (!Array.isArray(this.form.paperConfigGroupList)) {
      this.$set(this.form, "paperConfigGroupList", []);
    }
  },
  methods: {
    async loadDicts() {
      this.dictCache.has_examined = this.dict.label.has_examined;
    },
    /** 查询试卷信息设置列表 */
    getList() {
      this.loading = true;
      getPaperCofigList(this.queryParams).then((response) => {
        this.paperConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        paperConfigId: null,
        trainingProjectId: null,
        projectMap: null,
        singleChoiceCount: null,
        multipleChoiceCount: null,
        judgmentCount: null,
        totalCount: null,
        hasExamined: null,
        usageCount: null,
        scorePerQuestion: null,
        totalScore: null,
        paperConfigRemark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        exampleOne: null,
        exampleTwo: null,
        exampleThree: null,
        exampleFour: null,
        exampleFive: null,
        paperConfigGroupList: [],
        paperConfigName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 将时间范围拆分为 start 和 end
      if (this.queryParams.createTimeRange) {
        this.queryParams.createStartTime = this.queryParams.createTimeRange[0];
        this.queryParams.createEndTime = this.queryParams.createTimeRange[1];
        this.queryParams.createTime = null;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.createTimeRange = null;
      this.queryParams.trainingProjectId = null;    
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.paperConfigId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增试题";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const paperConfigId = row.paperConfigId || this.ids;

      getPaperConfigInfo(paperConfigId).then((response) => {
        //字段映射
        const mappedGroupList = response.data.paperConfigGroupList
          ? response.data.paperConfigGroupList.map((item) => ({
              // 后端字段 => 前端字段
              groupName: item.groupName || item.name || "",
              type: item.type || item.groupType || "",
              count: item.count || item.questionCount || 0,
              setCount: item.setCount || item.propositionCount || 0,
              scorePerQuestion:
                item.scorePerQuestion || item.scoreQuestion || 0,
              totalScore:
                item.totalScore || item.setCount * item.scorePerQuestion || 0,
              // 保留其他字段
              ...item,
            }))
          : [];

        this.form = {
          ...response.data,
          paperConfigGroupList: mappedGroupList,
        };

        console.log(
          "this.form.paperConfigGroupList",
          this.form.paperConfigGroupList
        );

        this.open = true;
        this.title = "编辑试题";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 构造提交数据
          const submitData = {
            ...this.form,
            paperConfigGroupList: this.form.paperConfigGroupList.map(
              (group) => ({
                ...group,
                propositionCount: group.setCount,
                scoreQuestion: group.scorePerQuestion,
                totalScore:
                  (group.setCount || 0) * (group.scorePerQuestion || 0),
              })
            ),
          };

          // 计算总题量和总分
          const totals = submitData.paperConfigGroupList.reduce(
            (acc, group) => {
              acc.totalCount += group.setCount || 0;
              acc.totalScore +=
                (group.setCount || 0) * (group.scorePerQuestion || 0);
              return acc;
            },
            { totalCount: 0, totalScore: 0 }
          );

          submitData.totalCount = totals.totalCount;
          submitData.totalScore = totals.totalScore;

          // 提交
          if (this.form.paperConfigId != null) {
            // 修改
            editPaperConfig(submitData).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增
            addPaperConfigInfo(submitData).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const paperConfigIds = row.paperConfigId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除试卷信息设置编号为"' + paperConfigIds + '"的数据项？'
        )
        .then(function () {
          return delPaperConfig(paperConfigIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "examination/paperConfig/export",
        {
          ...this.queryParams,
        },
        `paperConfig_${new Date().getTime()}.xlsx`
      );
    },

    //新增方法
    //树形结构
    filterTree() {
      this.$refs.tree.filter(this.projectName);
    },
    // 获取树形数据
    getProjectTree(val) {
      var params = { projectName: val };
      params.projectId = this.queryParams.trainingProjectId;
      projectTreeSelect(params).then((response) => {
        this.projectOptions = response.data;
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.queryParams.trainingProjectId = data.id;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 添加一行题组
    addRow() {
      this.form.paperConfigGroupList.push({
        groupName: "",
        type: "single",
        count: 0,
        setCount: 0,
        scorePerQuestion: 0,
        totalScore: 0,
      });
    },

    // 删除一行
    removeRow(index) {
      this.form.paperConfigGroupList.splice(index, 1);
    },
    //处理题组下拉框变化
    handleGroupChange(value, row) {
      // 如果是新创建的值，将其加入到选项列表中
      const exists = this.getGroupOptions(row.type).some(
        (option) => option.value === value
      );
      // if (!exists) {
      //   if (!this.customGroupOptions) {
      //     this.$set(this, "customGroupOptions", {});
      //   }

      //   if (!this.customGroupOptions[row.type]) {
      //     this.$set(this.customGroupOptions, row.type, []);
      //   }

      //   // 添加新选项
      //   this.customGroupOptions[row.type].push({
      //     value: value,
      //     label: value,
      //   });
      // }
    },

    // 获取题组选项（示例）
    getGroupOptions(type) {
      const baseOptions = [];
      // // 合并基础选项和自定义选项
      // if (this.customGroupOptions && this.customGroupOptions[type]) {
      //   return [...baseOptions, ...this.customGroupOptions[type]];
      // }

      return baseOptions;
    },
    handleProjectChange(value) {
      // value 是选中的项目ID
      if (value) {
        console.log("项目ID:", value);
        var params = { trainingProjectId: value };
        getListInfo(params)
          .then((response) => {
            // 确保 form 对象存在
            if (!this.form) {
              this.form = { paperConfigGroupList: [] };
            }

            // 检查响应结构并正确提取数据
            let paperConfigGroupListData = [];
            if (response.rows && Array.isArray(response.rows)) {
              // 分页数据格式
              paperConfigGroupListData = response.rows;
            } else if (Array.isArray(response)) {
              // 直接数组格式
              paperConfigGroupListData = response;
            } else if (response.data && Array.isArray(response.data)) {
              // data字段包含数组
              paperConfigGroupListData = response.data;
            }

            this.$set(
              this.form,
              "paperConfigGroupList",
              paperConfigGroupListData
            );

            console.log("题组列表:", this.form.paperConfigGroupList);
          })
          .catch((error) => {
            console.error("获取题组信息失败:", error);
            if (!this.form) {
              this.form = { paperConfigGroupList: [] };
            } else {
              this.$set(this.form, "paperConfigGroupList", []);
            }
          });
      }
    },
    getSummaryMethod({ columns, data }) {
      const result = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          result.push("合计");
        } else if (index === 3) {
          // 设置题量列
          const sum = data.reduce(
            (total, row) => total + (row.setCount || 0),
            0
          );
          result.push(sum);
        } else if (index === 4) {
          // 分数合计列
          const sum = data.reduce(
            (total, row) =>
              total + (row.setCount || 0) * (row.scorePerQuestion || 0),
            0
          );
          result.push(sum);
        } else {
          result.push("");
        }
      });
      return result;
    },
    // 映射字典数据
    getTypeLabel(type) {
      const typeMap = {
        single: "1",
        multiple: "2",
        judgment: "3",
      };
      return typeMap[type] || type;
    },
  },
  watch: {
    projectName(val) {
      this.$refs.tree.filter(val);
      this.getProjectTree(val);
    },
  },
};
</script>


<style scoped>
.app-container {
  display: flex;
  height: 100%;
}

.tree-panel {
  width: 360px;
  border-right: 1px solid #ebeef5;
  overflow-y: auto;
  padding: 20px;
}

.head-container {
  margin-bottom: 20px;
}

/* 弹窗样式调整 */
.el-dialog__body {
  padding: 20px 30px;
}

/* 表格样式调整 */
.el-table .cell {
  white-space: nowrap;
}

/* 按钮样式调整 */
.dialog-footer {
  text-align: center;
  padding: 20px 0;
}

.dialog-footer .el-button {
  margin: 0 10px;
}
</style>


